<?php

namespace App\V3\V3_2\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use App\Helper\Utils\TimeUtil;
use App\V3\V3_2\Services\ReceiptService;
use App\V3\V3_2\Models\ReceiptModel;
use App\V3\V3_2\Models\AdminAddendumModel;
use OSS\OssClient;
class ReceiptController extends BaseController
{
    protected $ossClient;
    public function __construct(Request $request){
        parent::__construct($request);
        $this->ossClient=new OssClient(
            config('app.aliyun_oss_key'),
            config('app.aliyun_oss_secret'),
            config('app.aliyun_oss_endpoint')
            );
    }
    /**
     * 添加收据
     */
    public function add(Request $request){

        $admininfo   = AdminAddendumModel::select('is_vip','empty_bill_amount')->where(['main_id'=>$this->getMainUserId()])->first()->toArray();

        if(!empty($admininfo) && in_array($admininfo['is_vip'],[1,2])){

         /*    $total_amount = DispatchListService::countReceiptsTotal(['main_id'=>$this->getMainUserId()]);

            if($admininfo['empty_bill_amount'] != -1 && $total_amount >= $admininfo['empty_bill_amount']){

                return $this->fail('','您创建的收据，已达到设置数量！');
            } */

        }else{

            return $this->fail('','您还不是VIP会员，还不能创建空白单据！');
        }
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'money'          =>'numeric|min:0',//金额

        ],[
            'money.numeric'   => '金额只能为数字',
            'money.min'       => '金额最小只能为0',

        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        if(!empty($unit_stamp_files = $request->file('unit_stamp'))){

            if($unit_stamp_files->isValid()){

                $img_path = $unit_stamp_files->store('yz/imgs/'.date('Y').'-'.date('m').'-'.date('d'));

                $imgRes  = self::addOssUploadImg($this->getMainUserId(),$this->ossClient, $unit_stamp_files, $img_path);
                if($imgRes['code'] === 0){
                    $data['unit_stamp'] = $imgRes['data'];
                }else{
                    return response()->json($imgRes);
                }
            }else{
                return response()->json(['code' => 1,'msg' => '单位印章，添加失败！','data' => '']);
            }
        }
        //开启事务
       DB::beginTransaction();
        try{
            //收据
            $dData = $data;
            $dData['created_at']   = time();
            $dData['user_id']      = $this->getUserId();
            $dData['main_id']      = $this->getMainUserId();

            if(empty($dData['receipt_no'])){

                $dData['receipt_no']  = 'NO.'. $this->getMainUserId().TimeUtil::getMillisecond();//收据号

            }else{

                $condition['receipt_no'] = $dData['receipt_no'];
                $condition['user_id']  = $this->getUserId();
                $condition['main_id']  = $this->getMainUserId();

                $info = ReceiptService::getReceiptInfo($condition);

                if(!empty($info)){

                    return $this->fail('','收据编号,已存在！');
                }
            }

            ReceiptService::add($dData);

            DB::commit();//提交事务
            $this->log("添加收据", $dData);
            return $this->success();
        }catch (\Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加收据');
        }

    }

    /**
     * 删除收据信息
     * @param ids (删除多个逗号分隔)
     */
    public function delete(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'ids'       =>'required',//收据id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }

        $id_data = [];
        $id_arr  = explode(',',$data['ids']);

        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();

        $list = ReceiptModel::select('id','unit_stamp')->where($condition)->whereIn('id',$id_arr)->get()->toArray();

        if(!empty($list)){

            foreach ($list as $k=>$v){

                $id_data[]=$v['id'];
            }
            DB::beginTransaction();
            try {

            $bool = ReceiptModel::where($condition)->whereIn('id',$id_data)->delete();;

            if($bool){
                foreach ($list as $gv){
                    if(!empty($gv['unit_stamp'])){

                        $delOssRes = self::delOssFilePath($gv['unit_stamp'], $this->ossClient, $this->getMainUserId());
                        if(!empty($delOssRes)) return $this->fail('',$delOssRes);
                    }
                }
                DB::commit();
                $this->log("删除收据", $id_arr);
                return $this->success();

            }else{
                return $this->fail('','删除失败');
            }

            } catch (\Exception $e) {
                return $this->fail('',$e->getMessage());
            }
        }
        return $this->fail('','收据，不存在！');
    }

    /**
     * 修改收据
     *
     */
    public function update(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'receipt_id'     =>'required|integer',//收据id
            'money'          =>'numeric|min:0',//金额

        ],[
            'receipt_id.required'   => '收据主键id缺失',
            'receipt_id.integer'   => '收据主键id为正整数',
            'money.numeric'   => '金额只能为数字',
            'money.min'       => '金额最小只能为0',

        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        if(!empty($unit_stamp_files = $request->file('unit_stamp'))){

            if($unit_stamp_files->isValid()){

                $img_path = $unit_stamp_files->store('yz/imgs/'.date('Y').'-'.date('m').'-'.date('d'));

                $imgRes  = self::addOssUploadImg($this->getMainUserId(),$this->ossClient, $unit_stamp_files, $img_path);
                if($imgRes['code'] === 0){
                    $data['unit_stamp'] = $imgRes['data'];
                }else{
                    return response()->json($imgRes);
                }
            }else{
                return response()->json(['code' => 1,'msg' => '单位印章，修改失败！','data' => '']);
            }
        }

        $info = ReceiptService::getReceiptInfo(['id'=> $data['receipt_id']]);

        if(empty($info)){

            return $this->fail('','收据号,不存在！');
        }
        //开启事务
        DB::beginTransaction();
        try{
            //收据
            $updData = $data;

            $condition['user_id'] = $this->getUserId();
            $condition['main_id'] = $this->getMainUserId();
            $condition['id']      = $updData['receipt_id'];

            unset($updData['receipt_id']);
            $updData['updated_at'] = time();

            $bool=ReceiptService::update($condition,$updData);
            if($bool){
                if(!empty($unit_stamp_files = $request->file('unit_stamp'))){
                    //删除oss里的文件
                    $delOssRes = self::delOssFilePath($info['unit_stamp'], $this->ossClient, $this->getMainUserId());
                    if(!empty($delOssRes)){

                        return $this->fail('',$delOssRes);
                    };
                }
            }
            DB::commit();//提交事务
            $this->log("修改收据", $updData);
            return $this->success();
        }catch (\Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'修改收据');
        }

    }

    /**
     * 收据信息
     * @param receipt_id
     */
    public function find(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'receipt_id'       =>'required|integer',//收据id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }

        $condition['id'] = $data['receipt_id'];
        $info = ReceiptService::getReceiptInfo($condition);
        $this->log("收据信息", $info);
        return $this->success($info);
    }

    /**
     * 收据列表
     */
    public function ReceiptList(Request $request){
       //参数验证
        $validator = Validator::make($data = $request->all(), [
            'page_size' =>'required|integer',//页面大小
            'current_page' =>'required|integer',//当前页
        ], [
            'page_size.required' => '参数`页面大小`丢失',
            'page_size.integer' => '参数`页面大小`仅能为数字',
            'current_page.required' => '参数`当前页码`丢失',
            'current_page.integer' => '参数`当前页码`仅能为数字',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $id_arr = [];
        $receipt_id_arr = [];

        $keyword = empty($data['keyword'])?'':$data['keyword'];
    if($this->getMainUserId() != 0){
        if($this->getUserId() == $this->getMainUserId()) {
                $condition['main_id'] = $this->getMainUserId();
            }
            else {
                if($this->isShareBillhead()) {

                    $condition['main_id'] = $this->getMainUserId();
                }else {
                    $condition['main_id'] = $this->getMainUserId();
                    $condition['user_id'] = $this->getUserId();
                }
            }
        }else{
            $condition['user_id'] = $this->getUserId();
        }
        if(!empty($keyword)){

            $list = ReceiptModel::select('id')->where($condition)
            ->where(function($query) use ($keyword) {
                $query->orWhere('receipt_no', 'like', '%'.$keyword.'%');
                $query->orWhere('accountant', 'like', '%'.$keyword.'%');
                $query->orWhere('teller', 'like', '%'.$keyword.'%');
                $query->orWhere('handling_person', 'like', '%'.$keyword.'%');
            })->orderBy('id','desc')
            ->get()->toArray();

            if(!empty($list)){

                foreach ($list as $k=>$v){

                    $id_arr[$k] = $v['id'];
                }
            }

            $receipt_id_arr = array_unique($id_arr);

            if(empty($receipt_id_arr)){

                $receipt_id_arr[0] ="0";
            }
        }

        $list = ReceiptService::getList($condition,$receipt_id_arr,$data['page_size'],$data['current_page']);

        $this->log("收据列表", $list);
        return $this->success($list);

    }

    /**
     * 图片上传到oss系统
     * @param unknown $client
     * @param unknown $file
     */
    static public function addOssUploadImg($mainId,$client,$file,$path){
        $res = handleUploadFileType($file);
        if(!empty($res)) return $res;
        $size = $file -> getSize();
         $result = saveFileSize(['main_id'=>$mainId], $size,$path);
         if($result['code'] == 1) return $result;
        try {

            $fullPath = '/uploads/'.$path;
            $ossPath  = ltrim($fullPath,'./');
            $path     = public_path().$fullPath;
            $client -> uploadFile(config('app.aliyun_oss_bucket'), $ossPath, $path);
            @unlink($path);
            $url = config('app.aliyun_oss_bucket_url').$fullPath;
            return ["code"=>0,"msg"=>"success","data"=>$url];

        } catch (\Exception $e) {

            return ["code"=>1,"msg"=>"OSS系统，上传图片失败！","data"=>""];
        }
    }

    /**
     * 删除oss里的文件
     * @param unknown $file
     * @param unknown $mainId
     */
    static public function delOssFilePath($file,$client,$mainId){
        if(empty($file)) return $file;
            DB::beginTransaction();
            try {
                $delPath = strstr($file, 'uploads/');
                $imgInfo=$client->getObjectMeta(config('app.aliyun_oss_bucket'), $delPath);
                AdminAddendumModel::where(['main_id'=>$mainId])
                ->decrement('file_total_size', $imgInfo['content-length']);
                $client -> deleteObject(config('app.aliyun_oss_bucket'), $delPath);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return "";
            }
    }

}
